package com.hanqi.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hanqi.entity.SysUser;
import com.hanqi.service.SysUserService;
import com.hanqi.util.R;
import com.hanqi.util.UUIDGenerator;
import com.hanqi.util.shiro.ShiroUtil;
import com.hanqi.util.shiro.UnamePwordToken;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zjk
 * @since 2019-04-27
 */
@Controller
@RequestMapping("/sysUser")
public class SysUserController {

    @Autowired
    protected SysUserService sysUserService;

    @RequestMapping("/index")
    public String index() {
        return "page/userList";
    }

    /**
     * 登陆验证请求
     *
     * @param user 用户对象
     * @param mav  数据视图模型
     * @return
     */
    @PostMapping("/login")
    public ModelAndView login(SysUser user, ModelAndView mav) {
        mav.setViewName("page/login");
        mav.addObject("user", user);
        if (user == null || (StringUtils.isEmpty(user.getUname()) && StringUtils.isEmpty(user.getPword()))) {
            mav.addObject("errorMsg", "请输入用户名和密码 !");
            return mav;
        }
        if (StringUtils.isEmpty(user.getUname())) {
            mav.addObject("unameErrorMsg", "用户名不能为空 !");
            return mav;
        }
        if (StringUtils.isEmpty(user.getPword())) {
            mav.addObject("pwordErrorMsg", "密码不能为空 !");
            return mav;
        }

        Subject subject = ShiroUtil.getSubject();
        UnamePwordToken token = new UnamePwordToken();
        token.setUsername(user.getUname());
        token.setPassword(user.getPword());
        try {
            subject.login(token);
        } catch (UnknownAccountException ue) {
            mav.addObject("errorMsg", "帐号可能不存在 !");
            return mav;
        } catch (AuthenticationException e) {
            mav.addObject("errorMsg", "密码不正确 !");
            return mav;
        }
        mav.setViewName("redirect:/index");
        return mav;
    }

    @ResponseBody
    @RequestMapping("/list")
    public List<SysUser> list() {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_flag", 0);
        return sysUserService.list(queryWrapper);
    }

    @ResponseBody
    @RequestMapping("/insert")
    public JSONObject insert(SysUser sysUser) {
        sysUser.setId(UUIDGenerator.getUUID());
        String salt = UUIDGenerator.getShortUUID();
        sysUser.setSalt(salt);
        sysUser.setPword(ShiroUtil.sha256(sysUser.getPword(), salt));
        sysUser.setCreateDate(LocalDateTime.now());
        sysUser.setCreateName(ShiroUtil.getUserEntity().getRname());
        sysUser.setDeleteFlag(0);
        boolean r = sysUserService.save(sysUser);
        if (r) {
            return R.SUCCESS;
        }
        return R.FAIL;
    }

    @ResponseBody
    @RequestMapping("/update")
    public JSONObject update(SysUser sysUser) {
        String pword = sysUser.getPword();
        SysUser orgSysUser = sysUserService.getById(sysUser.getId());
        if (pword != null && !StringUtils.equals(pword, orgSysUser.getPword())) {
            String secretPword = ShiroUtil.sha256(pword, orgSysUser.getSalt());
            sysUser.setPword(secretPword);
        }
        boolean r = sysUserService.updateById(sysUser);
        if (r) {
            return R.SUCCESS;
        }
        return R.FAIL;
    }

    @ResponseBody
    @RequestMapping("/delete")
    public JSONObject delete(String ids) {
        String[] idCollect = ids.split(",");
        boolean r = sysUserService.removeByIds(Arrays.asList(idCollect));
        if (r) {
            return R.SUCCESS;
        }
        return R.FAIL;
    }

    /**
     * 退出登陆
     *
     * @return
     */
    @GetMapping("/logout")
    public String logout() {
        ShiroUtil.logout();
        return "page/login";
    }
}
